package com.dong.order.config;

import com.dong.basic.tools.ConnectionTools;
import com.dong.order.service.OrderMessageOrderService;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.concurrent.TimeoutException;


@Configuration
public class RabbitConfig  {
    @Autowired
    private OrderMessageOrderService orderMessageService;

    /**
     * 自动执行????
     *  这里在启动时会进行调用, 用于自动装配. 比较讨巧
     */
    @Autowired
    public void startListenMassage() {
        orderMessageService.handleMessage();
    }

    @Bean
    public Channel channel() throws IOException, TimeoutException {
        ConnectionFactory connectionFactory = ConnectionTools.getConnectionFactory();
        Connection connection = connectionFactory.newConnection();
        Channel channel = connection.createChannel();
        channel.confirmSelect(); //开启发送端确认
        channel.basicQos(5);//消费端限流
        return channel;
    }
    @Bean
    public RabbitAdmin rabbitAdmin() {
        CachingConnectionFactory cf = new CachingConnectionFactory();
        cf.setHost("aliyun");
        cf.setPort(5672);
        cf.setUsername("root");
        cf.setPassword("dong054977");
        RabbitAdmin rabbitAdmin = new RabbitAdmin(cf);
        return rabbitAdmin;
    }
}
